<?php
class App_Order_Gift
{
    public static function shareImageUrl ($orderDetail)
    {
        $goodsList = Arr::get($orderDetail, 'arrGoodsInfo', array());
        $goods     = Arr::get($goodsList, 0, array());
        $goods     = Arr::get($goods, 'goods');
        $thumb     = Arr::get($goods, 'thumbsrc', '');
        $url       = url::site($thumb, 'http', FALSE);

        return $url;
    }

    public static function listByUser($user)
    {
        $uid   = $user->getUserUid();
        $query = DB::select('u.*', 'o.orderNo', array('o.id', 'orderId'),
            'o.status')
                ->from(array('app_order_gift', 'u'))
                ->join(array('app_order', 'o'), 'LEFT')
                ->on('u.orderNo', '=', 'o.orderNo')
                ->where('o.uid', '=', $uid)
                ->order_by('u.created', 'desc')
                ->execute();

        $ret = array();
        foreach ($query as $rs)
        {
            $orderNo = $rs['orderNo'];
            $orderDetail = App_Order::detail($orderNo);

            $rs['countsGoods'] = Arr::get($orderDetail, 'countsGoods', 0);
            $rs['shortTitle']  = utf8::substr($orderDetail['title'], 0, 15). '...';
            foreach ($orderDetail['arrGoodsInfo'] as $goods)
            {
                $rs['thumbSrc'] = $goods['goods']['thumbsrc'];
                break;
            }

            $ret[] = $rs;
        }

        return $ret;
    }

    public static function setDeliverNo ($orderNo, $uid, $deliverNo)
    {
       $rows = DB::update('app_order_gift')
            ->set(array('deliverNo' => $deliverNo, 'changed' => DB::expr('unix_timestamp(now())')))
            ->where('orderNo', '=', $orderNo)
            ->where('uid', '=', $uid)
            ->limit(1)
            ->execute();
    }

    public static function addGift ($orderNo, $user, $addrId)
    {
        $userUid = $user->getUserUid();
        $order   = App_Order::detail($orderNo);
        $countsGoods = Arr::get($order, 'countsQuantity', 0);
        $orderUid    = Arr::get($order, 'uid', 0);

        if ($userUid == $orderUid)
            return;

        $countsGift = self::countsGift($orderNo);
        if ($countsGoods <= $countsGift)
            return;

        // 订单状态允许增加礼物子订单
        if ($order['status'] > 0 && $order['status'] <= 3)
        {
            //
        }
        else
        // 订单状态禁止增加礼物子订单
        {
            return;
        }

        
        $time = DB::expr('unix_timestamp(now())');
        $row  = array(
            'orderId' => Arr::get($order, 'id'),
            'orderNo' => $orderNo,
            'uid'     => $userUid,
            'deliverNo' => '',
            'created'   => $time,
            'changed'   => $time,
        );

	    $address   = App_Address::detail($addrId);
	    $row['addrUserName'] = Arr::get($address, 'userName');
	    $row['addrTelNumber'] = Arr::get($address, 'telNumber');
	    $row['addrDetailInfo'] = $address['proviceName'] . 
            $address['cityName'].$address['countryName'].$address['detailInfo'];
	    $row['addrPostalCode'] = Arr::get($address, 'postalCode');
        
        list($insert_id, $rows) = DB::insert('app_order_gift')
            ->columns (array_keys($row))
            ->values (array_values($row))
            ->execute();

        if ($insert_id > 0)
        {
            // 发送微信领取礼物通知
	        $oLink     = url::site('/order/gift/'.$orderNo, 'http', FALSE);
	        $oBuyerUid = Arr::get($order, 'uid');
	        $message   = "你有一份礼物被{$row['addrUserName']}领走了。<a href=\"$oLink\">查看详情</a>";
	        App_Message::sendUserCustomMessage($oBuyerUid, $message);
        }
    }

    public static function detail ($orderNo, $user = NULL)
    {
        $query = DB::select()
            ->from('app_order_gift')
            ->where('orderNo', '=', $orderNo)
            ->execute();

        $userUid = empty($user) ? -1 : $user->getUserUid();
        $counts = $query->count();
        $users  = array();
        foreach ($query as $rs)
        {
            $uid = $rs['uid'];
            $users[$uid] = $rs;
        }

        $ret = array(
            'users' => $users,
            'userHasGift' => isset($users[$userUid]) ? 1 : 0,
            'userAddress' => Arr::get($users, $userUid, array()),
            'countsGift'  => $counts,
        );

        return $ret;
    }

    public static function countsGift($orderNo)
    {
        return DB::select(array('count("*")', 'counts'))
            ->from('app_order_gift')
            ->where('orderNo', '=', $orderNo)
            ->execute()
            ->get('counts');
    }
}
